package org.example.atomictest.longadder;

import lombok.extern.slf4j.Slf4j;
import org.example.utils.Sleeper;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhengdp
 * @Description
 * @Date 2022/11/27 18:09
 * @Created by zhengdp
 */
@Slf4j(topic = "c.LockCAS")
public class LockCAS {

    public static void main(String[] args) {
        LockCAS lock = new LockCAS();
        new Thread(() -> {
            log.info("begin ..");
            lock.lock();
            try{
                log.info("lock ...");
                Sleeper.sleep(1000);
            }finally {
                lock.unlock();
            }
        }).start();
        new Thread(() -> {
            log.info("begin ..");
            lock.lock();
            try{
                log.info("lock ...");
                Sleeper.sleep(1000);
            }finally {
                lock.unlock();
            }
        }).start();
    }
    // 0 : 没加锁  1 ： 加锁
    private AtomicInteger state = new AtomicInteger(0);

    public void lock() {
        while (true) {
            if (state.compareAndSet(0,1)) {
                break;
            }
        }
    }

    public void unlock() {
        log.info("unlock ...");
        state.set(0);
    }
}
